﻿using System;
using System.Linq;
using System.Windows;
using System.Xml.Linq;
using Microsoft.Win32;
using PengSW.ObservableCollectionHelper;
using static PengSW.RuntimeLog.RL;

namespace ProtocolAnalyzer
{
    /// <summary>
    /// RulesEdit.xaml 的交互逻辑
    /// </summary>
    public partial class RulesEdit : Window
    {
        public RulesEdit(AnalyzeModel aModel)
        {
            InitializeComponent();
            _Rules = aModel.Rules;
            this.DataContext = aModel;
        }

        private ObservableCollectionEx<ProtocolRule> _Rules;

        private void OnNewRule_Click(object sender, RoutedEventArgs e)
        {
            _Rules.Add(new ProtocolRule());
        }

        private void OnNewPreDefine_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            _Rules.ActiveItem.PreDefines.Add(new PreDefine());
        }

        private void OnNewPreDefine_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Rules?.ActiveItem != null;
        }

        private void OnNewAutoResponse_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            _Rules.ActiveItem.AutoResponses.Add(new AutoResponse());
        }

        private void OnNewAutoResponse_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _Rules?.ActiveItem != null;
        }

        private void OnImportRules_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog aDlg = new OpenFileDialog
            {
                Title = "导入规则",
                Filter = "Xml 文件|*.xml|所有文件|*.*",
            };
            if (aDlg.ShowDialog() != true) return;
            try
            {
                XDocument aXDocument = XDocument.Load(aDlg.FileName);
                foreach (XElement aXElement in aXDocument.Root.Elements(nameof(ProtocolRule)))
                {
                    ProtocolRule aRule = new ProtocolRule();
                    aRule.ReadFromXml(aXElement);
                    _Rules.Add(aRule);
                }
            }
            catch (Exception ex)
            {
                E(ex, "Import Rule");
            }
        }

        private void OnExportRules_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog aDlg = new SaveFileDialog
            {
                Title = "导出规则",
                Filter = "Xml 文件|*.xml|所有文件|*.*",
            };
            if (aDlg.ShowDialog() != true) return;
            try
            {
                XDocument aXDocument = new XDocument(new XElement("ProtocolRules", from r in _Rules select r.CreateXElement(nameof(ProtocolRule))));
                aXDocument.Save(aDlg.FileName);
            }
            catch (Exception ex)
            {
                E(ex, "Import Rule");
            }
        }
    }
}
